package com.familytree.controller;

import com.familytree.common.response.Result;
import com.familytree.dto.MemberTreeDTO;
import com.familytree.entity.ChildRequest;
import com.familytree.entity.MemberRequest;
import com.familytree.entity.SpouseRequest;
import com.familytree.model.Member;
import com.familytree.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/members")
@RequiredArgsConstructor
public class MemberController {

    private final MemberService memberService;

    @GetMapping
    public Result<?> findAll(
            @RequestParam(required = false) String search,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Page<Member> members = memberService.findAll(search, PageRequest.of(page, size));
        return Result.success(members);
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        Member member = memberService.findById(id);
        return Result.success(member);
    }

    @GetMapping("/search")
    public Result<?> search(
            @RequestParam String query,
            @RequestParam(defaultValue = "name") String type) {
        List<Member> members = memberService.search(query, type);
        return Result.success(members);
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> create(@RequestBody @Valid MemberRequest request) {
        Member member = new Member();
        member.setName(request.getName());
        member.setBirthDate(request.getBirthDate());
        member.setDeathDate(request.getDeathDate());
        member.setGender(request.getGender());
        member.setRole(request.getRole());
        member.setAvatarUrl(request.getAvatarUrl());
        
        Member created = memberService.create(member);
        return Result.success(created);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> update(@PathVariable Long id, @RequestBody @Valid MemberRequest request) {
        Member member = new Member();
        member.setName(request.getName());
        member.setBirthDate(request.getBirthDate());
        member.setDeathDate(request.getDeathDate());
        member.setGender(request.getGender());
        member.setRole(request.getRole());
        member.setAvatarUrl(request.getAvatarUrl());
        
        Member updated = memberService.update(id, member);
        return Result.success(updated);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> delete(@PathVariable Long id) {
        memberService.delete(id);
        return Result.success("删除成功");
    }

    @PostMapping("/{id}/spouse")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> addSpouse(@PathVariable Long id, @RequestBody @Valid SpouseRequest request) {
        Member member = memberService.addSpouse(id, request.getSpouseId(), request.getMarriageDate());
        return Result.success(member);
    }

    @DeleteMapping("/{id}/spouse")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> deleteSpouse(@PathVariable Long id) {
        memberService.deleteSpouse(id);
        return Result.success("删除配偶成功");
    }

    @PostMapping("/{id}/children")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> addChild(@PathVariable Long id, @RequestBody @Valid ChildRequest request) {
        Member member = memberService.addChild(id, request.getChildId());
        return Result.success(member);
    }

    @GetMapping("/{id}/family-tree")
    public Result<?> getFamilyTree(@PathVariable Long id) {
        Map<String, Object> familyTree = memberService.getFamilyTree(id);
        return Result.success(familyTree);
    }

    @GetMapping("/tree")
    public Result<?> getFamilyTree() {
        try {
            MemberTreeDTO tree = memberService.getFamilyTree();
            return Result.success(tree);
        } catch (Exception e) {
            return Result.error("获取家族树失败：" + e.getMessage());
        }
    }

    @PutMapping("/{id}/avatar")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> updateAvatar(@PathVariable Long id, @RequestBody Map<String, String> request) {
        String avatarUrl = request.get("avatarUrl");
        if (avatarUrl == null || avatarUrl.isEmpty()) {
            return Result.error("头像URL不能为空");
        }
        
        Member member = memberService.findById(id);
        member.setAvatarUrl(avatarUrl);
        member.setUpdateDate(LocalDate.now());
        memberService.update(id, member);
        
        return Result.success("头像更新成功");
    }
}
